<?php

/**
 *   OPENSHOP 管理中心商店设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: shop_config.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

/* 代码 */
require(dirname(__FILE__) . '/includes/init.php');

/*------------------------------------------------------ */
//-- 列表编辑 act=list_edit
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list_edit')
{
    /* 检查权限 */
    admin_priv();

    $smarty->assign('ur_here',      '商店设置');
    $smarty->assign('group_list',   get_settings(null, array('5')));
    $smarty->assign('countries',    get_regions());

    if ($_CFG['shop_country'] > 0)
    {
        $smarty->assign('provinces', get_regions(1, $_CFG['shop_country']));
        if ($_CFG['shop_province'])
        {
            $smarty->assign('cities', get_regions(2, $_CFG['shop_province']));
        }
    }
    $smarty->assign('cfg', $_CFG);

    assign_query_info();    
    $smarty->display("shop_config.tpl");
}

/*------------------------------------------------------ */
//-- 邮件服务器设置
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'mail_settings')
{
    /* 检查权限 */
    admin_priv();

    $arr = get_settings(array(5));

    assign_query_info();

    $smarty->assign('ur_here',      '邮件服务器设置');
    $smarty->assign('cfg', $arr[5]['vars']);        
    $smarty->display("shop_config_mail_settings.tpl");    
}

/*------------------------------------------------------ */
//-- 提交   ?act=post
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'post')
{
    $type = empty($_POST['type']) ? '' : $_POST['type'];
	
    /* 允许上传的文件类型 */
    $allow_file_types = '|GIF|JPG|PNG|BMP|SWF|DOC|XLS|PPT|MID|WAV|ZIP|RAR|PDF|CHM|RM|TXT|CERT|';

    /* 保存变量值 */
    $count = count($_POST['value']);

    $arr = array();
    $sql = 'SELECT id, value FROM ' . $os->table('shop_config');
    $res= $db->query($sql);
    while($row = $db->fetchRow($res))
    {
        $arr[$row['id']] = $row['value'];
    }
    
    foreach ($_POST['value'] AS $key => $val)
    {
    	if(is_array($val))
    	{
    		$subarr = explode(',', $arr[$key]);
    		foreach ($subarr AS $subkey => $subval)
    		{
    			$subarr[$subkey] = intval($val[$subkey]);
    		}
    		$sql = "UPDATE " . $os->table('shop_config') . " SET value = '" . implode(',', $subarr) . "' WHERE id = '" . $key . "'";
            $db->query($sql);
    	}
        elseif($arr[$key] != $val)
        {
            $sql = "UPDATE " . $os->table('shop_config') . " SET value = '" . trim($val) . "' WHERE id = '" . $key . "'";
            $db->query($sql);
        }
    }

    /* 处理上传文件 */
    $file_var_list = array();
    $sql = "SELECT * FROM " . $os->table('shop_config') . " WHERE parent_id > 0 AND type = 'file'";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $file_var_list[$row['code']] = $row;
    }

    foreach ($_FILES AS $code => $file)
    {
        /* 判断用户是否选择了文件 */
        if ((isset($file['error']) && $file['error'] == 0) || (!isset($file['error']) && $file['tmp_name'] != 'none'))
        {
            /* 检查上传的文件类型是否合法 */
            if (!check_file_type($file['tmp_name'], $file['name'], $allow_file_types))
            {
                sys_msg(sprintf('您上传了一个非法的文件类型。该文件名为：%s', $file['name']));
            }
            else
            {
            	$store_dir = $file_var_list[$code]['store_dir'];
                if ($code == 'shop_logo')
                {
                    include_once('includes/lib_template.php');
                    $info = get_template_info($_CFG['template']);

                    $file_name = str_replace('{$template}', $_CFG['template'], $file_var_list[$code]['store_dir']) . $info['logo'];
                    $store_dir = str_replace('{$template}', $_CFG['template'], $store_dir);
                }
                elseif ($code == 'watermark')
                {
                    $ext = array_pop(explode('.', $file['name']));
                    $file_name = $file_var_list[$code]['store_dir'] . 'watermark.' . $ext;
                    if ($filesync->sync_type!='ftp' && file_exists(SOURCE_PATH . $file_var_list[$code]['value']))
                    {
                        @unlink(SOURCE_PATH . $file_var_list[$code]['value']);
                    }
                }
                elseif($code == 'wap_logo')
                {
                    $ext = array_pop(explode('.', $file['name']));
                    $file_name = $file_var_list[$code]['store_dir'] . 'wap_logo.' . $ext;
                    if ($filesync->sync_type!='ftp' && file_exists(SOURCE_PATH . $file_var_list[$code]['value']))
                    {
                        @unlink(SOURCE_PATH . $file_var_list[$code]['value']);
                    }
                }
                else
                {
                    $file_name = $file_var_list[$code]['store_dir'] . $file['name'];
                }
                
			    if($filesync->sync_type=='ftp'){
			    	$filesync->connect();
			    	$filesync->setting('shop_config', trim(str_replace('../'.SOURCE_DIR.'/', '', $store_dir), '/'), FALSE);
			    	$filesync->set_updata(TRUE, $file_var_list[$code]['id'], 'shop_config');
				    $affix_data = $filesync->put_up($file);
				    
				    if ($affix_data !== false)
				    {
				        $file_name = $affix_data['virtual_path'];
				    }else{
				    	sys_msg(sprintf('上传文件 %s 失败，请检查 %s 目录是否可写。', $file['name'], $file_var_list[$code]['store_dir']));
				    }
				    $filesync->quit();		    
			    }else{
			    	if(!move_upload_file($file['tmp_name'], $file_name)){
			    		sys_msg(sprintf('上传文件 %s 失败，请检查 %s 目录是否可写。', $file['name'], $file_var_list[$code]['store_dir']));
			    	}
			    	$file_name = str_replace('../'.SOURCE_DIR.'/', '', $file_name);
			    }		                 
               
                $sql = "UPDATE " . $os->table('shop_config') . " SET value = '$file_name' WHERE code = '$code'";
                $db->query($sql);
            }
        }
    }

    /* 处理自动配货参数 */
    if ($_POST['auto_range_or_not'] >= 0)
    {
        $range = array($_POST['auto_range_or_not'], $_POST['auto_range_hours']);
        $sql = "UPDATE " . $os->table('shop_config') . " SET value = '" . serialize($range) . "' WHERE code = 'auto_range'";
        $db->query($sql);
    }
    
    /* 处理发票类型及税率 */
    if (!empty($_POST['invoice_rate']))
    {
        foreach ($_POST['invoice_rate'] as $key => $rate)
        {
            $rate = round(floatval($rate), 2);
            if ($rate < 0)
            {
                $rate = 0;
            }
            $_POST['invoice_rate'][$key] = $rate;
        }
        $invoice = array(
            'type' => $_POST['invoice_type'],
            'rate' => $_POST['invoice_rate']
        );
        $sql = "UPDATE " . $os->table('shop_config') . " SET value = '" . serialize($invoice) . "' WHERE code = 'invoice_type'";
        $db->query($sql);
    }

    /* 记录日志 */
    admin_log('', 'edit', 'shop_config');

    /* 清除缓存 */
    clear_all_files();

    $_CFG = load_config();

    $shop_country   = $db->getOne("SELECT region_name FROM ".$os->table('region')." WHERE region_id='$_CFG[shop_country]'");
    $shop_province  = $db->getOne("SELECT region_name FROM ".$os->table('region')." WHERE region_id='$_CFG[shop_province]'");
    $shop_city      = $db->getOne("SELECT region_name FROM ".$os->table('region')." WHERE region_id='$_CFG[shop_city]'");

    if ($type == 'mail_setting')
    {
        $links[] = array('text' => '返回邮件服务器设置', 'href' => 'shop_config.php?act=mail_settings');
        sys_msg('邮件服务器设置成功。', 0, $links);
    }
    else
    {
        $links[] = array('text' => '返回商店设置', 'href' => 'shop_config.php?act=list_edit');
        sys_msg('保存商店设置成功。', 0, $links);
    }
}

/*------------------------------------------------------ */
//-- 发送测试邮件
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'send_test_email')
{
    /* 取得参数 */
    $email          = trim($_POST['email']);

    /* 更新配置 */
    $_CFG['mail_service'] = intval($_POST['mail_service']);
    $_CFG['smtp_host']    = trim($_POST['smtp_host']);
    $_CFG['smtp_port']    = trim($_POST['smtp_port']);
    $_CFG['smtp_user']    = json_str_iconv(trim($_POST['smtp_user']));
    $_CFG['smtp_pass']    = trim($_POST['smtp_pass']);
    $_CFG['smtp_mail']    = trim($_POST['reply_email']);
    $_CFG['mail_charset'] = trim($_POST['mail_charset']);

    if (send_mail('', $email, '测试邮件', '您好！这是一封检测邮件服务器设置的测试邮件。收到此邮件，意味着您的邮件服务器设置正确！您可以进行其它邮件发送的操作了！', 0))
    {
        make_json_result('', '恭喜！测试邮件已成功发送到' . $email);
    }
    else
    {
        make_json_error(join("\n", $err->_message));
    }
}

/*------------------------------------------------------ */
//-- 删除上传文件
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'del')
{
    /* 取得参数 */
    $code          = trim($_GET['code']);

    $filename = $_CFG[$code];

    //删除文件
    @unlink($filename);

    //更新设置
    update_configure($code, '');

    /* 记录日志 */
    admin_log('', 'edit', 'shop_config');

    /* 清除缓存 */
    clear_all_files();

    sys_msg('保存商店设置成功。', 0);

}

/**
 * 设置系统设置
 *
 * @param   string  $key
 * @param   string  $val
 *
 * @return  boolean
 */
function update_configure($key, $val='')
{
    if (!empty($key))
    {
        $sql = "UPDATE " . $GLOBALS['os']->table('shop_config') . " SET value='$val' WHERE code='$key'";

        return $GLOBALS['db']->query($sql);
    }

    return true;
}

/**
 * 获得设置信息
 *
 * @param   array   $groups     需要获得的设置组
 * @param   array   $excludes   不需要获得的设置组
 *
 * @return  array
 */
function get_settings($groups=null, $excludes=null)
{
    global $db, $os, $_LANG;

    $config_groups = '';
    $excludes_groups = '';

    if (!empty($groups))
    {
        foreach ($groups AS $key=>$val)
        {
            $config_groups .= " AND (id='$val' OR parent_id='$val')";
        }
    }
    
    if (!empty($excludes))
    {
        foreach ($excludes AS $key=>$val)
        {
            $excludes_groups .= " AND (parent_id<>'$val' AND id<>'$val')";
        }
    }

    /* 取出全部数据：分组和变量 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('shop_config') .
            " WHERE type<>'hidden' $config_groups $excludes_groups ORDER BY parent_id, sort_order, id";

    $item_list = $db->getAll($sql);

    /* 整理数据 */
    $group_list = array();
    foreach ($item_list AS $key => $item)
    {
    	if(($item['code'] != 'wap') && ($item['code'] != 'goods') && ($item['code'] != 'stock_dec_time'))
    	{
    		
	        $pid = $item['parent_id'];
	        $item['name'] = isset($_LANG['cfg_name'][$item['code']]) ? $_LANG['cfg_name'][$item['code']] : $item['code'];
	        $item['desc'] = isset($_LANG['cfg_desc'][$item['code']]) ? $_LANG['cfg_desc'][$item['code']] : '';
	
	        if ($pid == 0)
	        {
	            /* 分组 */
	            if ($item['type'] == 'group')
	            {
	                $group_list[$item['id']] = $item;
	            }
	        }
	        else
	        {
	            /* 变量 */
	            if (isset($group_list[$pid]))
	            {
	                if ($item['store_range'])
	                {
	                    $item['store_options'] = explode(',', $item['store_range']);
	
	                    foreach ($item['store_options'] AS $k => $v)
	                    {
	                        $item['display_options'][$k] = isset($_LANG['cfg_range'][$item['code']][$v]) ?
	                                $_LANG['cfg_range'][$item['code']][$v] : $v;
	                        if ($item['type'] == 'checkbox')
	                        {
	                        	$item['store_options'][$k] = 1;
	                        }
	                    }
	                }
	                if (strpos($item['value'], ',') > 0)
	                {
	                    $item['value'] = explode(',', $item['value']);
	                }
	                $group_list[$pid]['vars'][] = $item;
	            }
	        }
        
    	}

    }

    return $group_list;
}
?>